package com.jiandaoshou;

import android.graphics.Color;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.utils.Legend;
import com.jiandaoshou.adapter.DingDanRecyclerAdapter;
import com.jiandaoshou.base.BaseActivity;
import com.jiandaoshou.entry.DingDanDetailEntry;
import com.jiandaoshou.entry.PayModeEntry;
import com.jiandaoshou.http.APIDefine;
import com.jiandaoshou.http.Http;
import com.jiandaoshou.utils.DividerItemDecoration;
import com.jiandaoshou.utils.JsonUtil;
import com.jiandaoshou.utils.ScreenUtil;
import com.jiandaoshou.utils.TimeUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

public class MonthDingDanAct extends BaseActivity {
    private TextView Tv_Month;
    private RecyclerView mRecyclerView;
    private XRefreshView xRefreshView;
    private DingDanRecyclerAdapter adapter;
    private LinearLayoutManager LayoutManager;
    private List<DingDanDetailEntry> datas;
    private String shopID;
    private int page = 1, count = 10;
    private String starttime, endtime;
    //true下拉加载
    private boolean flag = true;
    private PieChart mPieChat;
    private TextView Tv_DingDanNum, Tv_DingDanJinE;
    private LinearLayout  Lin_Yuan;
    private TextView tvWXTJ;
    private TextView tvAliTJ;

    private FrameLayout flBiliTu;

    @Override
    public boolean showBackLogo() {
        return true;
    }

    @Override
    protected int getContentViewRes() {
        return R.layout.activity_monthdingdan;
    }

    @Override
    protected String getTitleText() {
        return "月订单";
    }

    @Override
    public void init() {
        datas = new ArrayList<DingDanDetailEntry>();
        Tv_Month = $(R.id.tv_month);
        mRecyclerView = $(R.id.month_recyclerview);
        xRefreshView = $(R.id.month_refresh);
        mPieChat = $(R.id.piechart);
        Tv_DingDanNum = $(R.id.text_dingdanliang);
        Tv_DingDanJinE = $(R.id.text_dingdanjine);
        Lin_Yuan=$(R.id.montndingdan_linear);
        tvWXTJ=$(R.id.tvWXTJ);
        tvAliTJ=$(R.id.tvAliTJ);
        flBiliTu=$(R.id.flBiTu);
        //给圆形设置长高
        int ScreenHeight=ScreenUtil.getInstant().getDisHight(this);
        LinearLayout.LayoutParams params= (LinearLayout.LayoutParams) Lin_Yuan.getLayoutParams();
        int Height=ScreenHeight/5;
        params.height=Height;
        params.width=Height;
        params.topMargin=25;
        params.bottomMargin=25;
        Lin_Yuan.setLayoutParams(params);
        //获取数据
        GetPieChartData();
        xRefreshView.setMoveForHorizontal(true);
        mRecyclerView.setHasFixedSize(true);
        //设置布局管理器
        LayoutManager = new LinearLayoutManager(this);
        LayoutManager.setOrientation(OrientationHelper.VERTICAL);
        mRecyclerView.setLayoutManager(LayoutManager);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        //设置增加或删除条目的动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setAutoLoadMore(true);
        xRefreshView.setHideFooterWhenComplete(false);
        adapter = new DingDanRecyclerAdapter(this, datas);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(this));
        mRecyclerView.setAdapter(adapter);
        GetData(page, 0);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page++;
                GetData(page, 2);
                xRefreshView.setLoadComplete(true);
                xRefreshView.stopLoadMore();
            }

            @Override
            public void onRefresh() {
                super.onRefresh();
                page = 1;
                datas.clear();
                GetData(page, 1);
                xRefreshView.stopRefresh();
            }
        });
    }

    //获取饼状图的数据
    private void GetPieChartData() {
        //根据支付方式不同获取数据
        shopID = getIntent().getStringExtra("shopID");
        String time = getIntent().getStringExtra("month").trim();
        int year = Integer.parseInt(time.substring(0, time.indexOf("-")));
        int n = Integer.valueOf(time.substring(time.indexOf("-")+1, time.indexOf("-")+2));
        int month = 0;
        if (n == 0) {
            month = Integer.valueOf(time.substring(time.indexOf("-")+2, time.length()));
        } else {
            month = Integer.valueOf(time.substring(time.indexOf("-")+1, time.length()));
        }
        starttime = TimeUtil.getInstance().getMonthBeginTime(year, month);
        endtime = TimeUtil.getInstance().getMonthEndTime(year, month);
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("strBeginTime", starttime);
        map.put("strEndTime", endtime);
        map.put("strShopID", shopID);
        map.put("strPayMode", "1,2,3,4,5");
        Http.post(APIDefine.TF_Interface_GETPAYMODETOTAL, map, new Http.HttpCallBack() {
            @Override
            public void onHttpSuccess(String response) throws Exception {
                PayModeEntry entry = JsonUtil.parser.fromJson(response, PayModeEntry.class);
                PieData mPieData = getPieData(entry);
                showChart(mPieChat, mPieData);
                int DingDanNum = entry.getPosCount() + entry.getWeixinCount() + entry.getApplePayCount() + entry.getYinlianCount() + entry.getZhifubaoCount();
                String str_pos = entry.getPosMoney();
                if(str_pos==null||str_pos.equals("")){
                    str_pos="0.0";
                }
                String str_weixin=entry.getWeixinMoney();
                if(str_weixin==null||str_weixin.equals("")){
                   str_weixin="0.0";
                }
                String str_Appler=entry.getApplePayMoney();
                if(str_Appler==null||str_Appler.equals("")){
                    str_Appler="0.0";
                }
                String str_yinlian=entry.getYinlianMoney();
                if(str_yinlian==null||str_yinlian.equals("")){
                    str_yinlian="0.0";
                }
                String str_zhifubao=entry.getZhifubaoMoney();
                if(str_zhifubao==null||str_zhifubao.equals("")){
                    str_zhifubao="0.0";
                }
                float num_pos=Float.valueOf(str_pos);
                float num_weixin=Float.valueOf(str_weixin);
                float num_Appler=Float.valueOf(str_Appler);
                float num_yinlian=Float.valueOf(str_yinlian);
                float num_zhifubao=Float.valueOf(str_zhifubao);
                float num_total=num_pos+num_weixin+num_Appler+num_yinlian+num_zhifubao;
                Tv_DingDanNum.setText("" + DingDanNum);
                Tv_DingDanJinE.setText("" + num_total);
            }
        });
    }

    private void showChart(PieChart pieChart, PieData pieData) {
        pieChart.setTransparentCircleRadius(0f); // 半透明圈
        pieChart.setHoleRadius(0f);  //实心圆
        pieChart.setDescription("");
        pieChart.setDrawCenterText(true);  //饼状图中间可以添加文字
        pieChart.setDrawHoleEnabled(true);
        pieChart.setRotationAngle(90); // 初始旋转角度
        pieChart.setRotationEnabled(true); // 可以手动旋转
        pieChart.setUsePercentValues(false);  //显示成百分比
        pieChart.setDrawXValues(false);
        pieChart.setDrawYValues(false);

        int screenHeight=ScreenUtil.getInstant().getDisHight(this);
        FrameLayout.LayoutParams params= (FrameLayout.LayoutParams) pieChart.getLayoutParams();
        int parent_size=screenHeight/5;
        params.height=(int) (parent_size*1f);
        params.width=(int) (parent_size*1f);
        pieChart.setLayoutParams(params);

        //设置数据
        pieChart.setData(pieData);
        Legend legend = pieChart.getLegend();  //设置比例图
        legend.setXEntrySpace(0f);
        legend.setYEntrySpace(5f);
        legend.setTextSize(0f);
        pieChart.animateXY(1000, 1000);  //设置动画
    }


    private PieData getPieData(PayModeEntry entry) {
        ArrayList<String> xValues = new ArrayList<String>();  //xVals用来表示每个饼块上的内容
        tvWXTJ.setText(String.format(getResources().getString(R.string.wx_tj),entry.getWeixinCount(),entry.getWeixinMoney()));
        tvAliTJ.setText(String.format(getResources().getString(R.string.ali_tj),entry.getZhifubaoCount(),entry.getZhifubaoMoney()));
        xValues.add("");
        xValues.add("");

        ArrayList<Entry> yValues = new ArrayList<Entry>();  //yVals用来表示封装每个饼块的实际数据
        // 饼图数据
        yValues.add(new Entry(Float.parseFloat(entry.getWeixinMoney()), 0));
        yValues.add(new Entry(Float.parseFloat(entry.getZhifubaoMoney()), 1));
        //y轴的集合
        PieDataSet pieDataSet = new PieDataSet(yValues, ""/*显示在比例图上*/);
        pieDataSet.setSliceSpace(0f); //设置个饼状图之间的距离
        ArrayList<Integer> colors = new ArrayList<Integer>();
        // 饼图颜色
        colors.add(Color.rgb(27,203,183));
        colors.add(Color.rgb(245,90,17));
        pieDataSet.setColors(colors);
        PieData pieData = new PieData(xValues, pieDataSet);
        return pieData;
    }

    //网络请求
    private void GetData(int page, final int type) {
        //获取网络请求的数据
        String str = getIntent().getStringExtra("type");
        if (str.equals("list")) {
            shopID = getIntent().getStringExtra("shopID");
            String time = getIntent().getStringExtra("month").trim();
            Tv_Month.setText(time);
            int year = Integer.parseInt(time.substring(0, time.indexOf("-")));
            int n = Integer.valueOf(time.substring(time.indexOf("-")+1, time.indexOf("-")+2));
            int month = 0;
            if (n == 0) {
                month = Integer.valueOf(time.substring(time.indexOf("-")+2, time.length()));
            } else {
                month = Integer.valueOf(time.substring(time.indexOf("-")+1, time.length()));
            }
            starttime = TimeUtil.getInstance().getMonthBeginTime(year, month);
            endtime = TimeUtil.getInstance().getMonthEndTime(year, month);
        } else {
            shopID = getIntent().getStringExtra("shopID");
            String time = getIntent().getStringExtra("month");
            Calendar a = Calendar.getInstance();
            int year = a.get(Calendar.YEAR);
            Tv_Month.setText(year + "-" + time);
            starttime = TimeUtil.getInstance().getMonthBeginTime(year, Integer.valueOf(time));
            endtime = TimeUtil.getInstance().getMonthEndTime(year, Integer.valueOf(time));
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("strEndTime", endtime);
        map.put("strBeginTime", starttime);
        map.put("strShopID", shopID);
        map.put("strPayMode", "");
        map.put("order", "desc");
        map.put("strShopSonName", "");
        map.put("sort", "dtTransactionTime");
        map.put("rows", count + "");
        map.put("page", page + "");
        Http.post(APIDefine.TF_Interface_GetOrderMsg, map, new Http.HttpCallBack() {
            @Override
            public void onHttpSuccess(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    JSONArray array = (JSONArray) object.get("OrderList");
                    if (array.length() == 0) {
                        xRefreshView.stopRefresh();
                        xRefreshView.stopLoadMore();
                        return;
                    }
                    DingDanDetailEntry entry;
                    for (int i = 0; i < array.length(); i++) {
                        entry = JsonUtil.parser.fromJson(array.get(i).toString(), DingDanDetailEntry.class);
                        datas.add(entry);
                    }
                    adapter.notifyDataSetChanged();
                    if (array.length() < count) {
                        xRefreshView.setLoadComplete(true);
                        xRefreshView.stopLoadMore();
                    } else {
                        xRefreshView.setLoadComplete(false);
                    }
                    if (type == 1) {
                        xRefreshView.stopRefresh();
                    } else {
                        xRefreshView.stopLoadMore();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
